<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 数字资源统计访问量
 */
class DigitalAccessNum extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;


    protected $table = 'digital_access_num';



    /**
     * 记录每日浏览量
     * @param id 数字阅读id
     */
    public function dayBrowse($id)
    {
        //获取当前年月日
        $yyy = date('Y');
        $mmm = intval(date('m'));
        $ddd = intval(date('d'));
        //先更新
        $res = $this->where('digital_id', $id)->where('yyy', $yyy)->where('mmm', $mmm)->where('ddd', $ddd)->first();
        if ($res) {
            //添加数据库
            $res->number = $res->number + 1;
            $res->save();
        } else {
            $this->number = 1;
            $this->digital_id = $id;
            $this->yyy = $yyy;
            $this->mmm = $mmm;
            $this->ddd = $ddd;
            $this->save();
        }
        return true;
    }

    /**
     * 数字资源点击量、图书到家点击量
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @param $digital_id 数字资源id
     */
    public function getClickNumber($digital_id = 1, $start_time = null, $end_time = null)
    {
        $number = $this->where(function ($query) use ($digital_id, $start_time, $end_time) {
            if ($digital_id) {
                $query->where('digital_id', $digital_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->sum('number');
        return $number;
    }

    /**
     * 点击量统计(折线图)
     * @param $digital_id 数字资源id
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     */
    public function clickStatistics($digital_id = null, $start_time = null, $end_time = null)
    {

        if (date('Y-m-d', strtotime($start_time)) == date('Y-m-d', strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as times"), DB::raw("sum(number) as number")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as times"), DB::raw("sum(number) as number")];
        }

        $res = $this->select($field)->where(function ($query) use ($digital_id, $start_time, $end_time) {
            if ($digital_id) {
                $query->where('digital_id', $digital_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->orderBy('times')
            ->groupBy('times')
            ->get()
            ->toArray();

        return $res;
    }
}
